﻿using System;
using System.Net.Sockets;

namespace GameServer.Network
{
    class Client
    {
        TcpClient _client = null;

        NetworkStream _stream = null;

        byte[] _buffer = new byte[1024*8];

        public Client(TcpClient client)
        {
            _client = client;
            Start();
        }

        private void Start()
        {
            _stream = _client.GetStream();
            _stream.BeginRead(_buffer, 0, _buffer.Length, new AsyncCallback(OnRecive), _stream);

            while (_client.Connected)
            {
                //
            }
        }

        public void Send(byte[] data)
        {
            Send(data, 0, data.Length);
        }

        public void Send(byte[] data, int size)
        {
            Send(data, 0, size);
        }

        public void Send(byte[] data, int offset, int size)
        {
            _stream.BeginWrite(data, offset, size, new AsyncCallback(OnSend), _stream);
        }

        private void OnRecive(IAsyncResult ar)
        {
            NetworkStream s = (NetworkStream)ar.AsyncState;
            int dataLength = s.EndRead(ar);

            if (dataLength > 0)
            {
                //
            }

            if (_client.Connected)
            {
                s.BeginRead(_buffer, 0, _buffer.Length, new AsyncCallback(OnRecive), s);
            }
        }

        private void OnSend(IAsyncResult ar)
        {
            NetworkStream s = (NetworkStream)ar.AsyncState;
            s.EndWrite(ar);
        }
    }
}
